package com.echo.boot.sync.waitandnotify;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/9/13
 * Time: 21:57
 */
public class Drop {
    private String food;
    // empty为true代表：消费者需要等待生产者生产食品
    // empty为false代表：食品生产完毕，生产者要等待消费者消化完食品
    private boolean empty = true;


    /**
     * get方法在消费者线程中执行
     *
     * @return
     */
    public synchronized String get() {
        while (empty) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }

        empty = true;
        notifyAll();
        return food;
    }

    /**
     * add方法在生产者线程中执行
     *
     * @param food
     */
    public synchronized void add(String food) {
        while (!empty) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }

        empty = false;
        this.food = food;
        notifyAll();
    }

}
